<template>
  <el-container class="platform-school">
    <el-main>
      <!-- 搜索和操作区 -->
      <el-card class="search-card">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input v-model="searchKeyword" placeholder="搜索学校名称/编号" clearable>
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="searchStatus" placeholder="选择状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="正常" value="true"></el-option>
              <el-option label="禁用" value="false"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </el-col>
          <el-col :span="6" class="text-right">
              <el-button 
                type="danger" 
                @click="handleBatchDelete" 
                :disabled="selectedSchools.length === 0"
                style="margin-right: 10px;"
              >
                <el-icon><Delete /></el-icon> 批量禁用
              </el-button>
              <el-button type="warning" @click="handleReview">
                <el-icon><Check /></el-icon> 审核
              </el-button>
            </el-col>
        </el-row>
      </el-card>

      <!-- 学校列表 -->
      <el-card class="school-list-card">
        <template #header>
          <div class="card-header">
            <span>学校管理</span>
            <span class="count">(共 {{ filteredSchools.length }} 所学校)</span>
          </div>
        </template>
        
        <el-table :data="paginatedSchools" v-loading="loading" stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
          <el-table-column label="学校" width="220">
            <template #default="scope">
              <div style="display: flex; align-items: center;">
                <el-avatar :size="40" :src="scope.row.avatar" style="margin-right: 10px;">
                  <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                </el-avatar>
                <div>
                  <div style="font-weight: 500;">{{ scope.row.realName }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ scope.row.number }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="地区信息">
            <template #default="scope">
              <div>{{ scope.row.province }}{{ scope.row.city }}{{ scope.row.district }}</div>
              <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                {{ scope.row.detailAddress || '无详细地址' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="学校代码" width="120"></el-table-column>
          <el-table-column prop="mobile" label="联系电话" width="130"></el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="scope">
              <div style="display: flex; align-items: center; justify-content: center;">
                <span :class="['status-badge', scope.row.status ? 'status-active' : 'status-inactive']"></span>
                <span>{{ scope.row.status ? '正常' : '禁用' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="最后登录" width="160">
            <template #default="scope">
              <div class="last-login-time">
                {{ formatTime(scope.row.lastLoginTime) || '从未登录' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <div class="table-actions">
                <el-button size="small" @click="handleViewDetail(scope.row)">查看</el-button>
                <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button 
                  size="small" 
                  :type="scope.row.status ? 'danger' : 'success'" 
                  @click="handleChangeStatus(scope.row)"
                >
                  {{ scope.row.status ? '禁用' : '启用' }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredSchools.length"
          ></el-pagination>
        </div>
      </el-card>
    </el-main>

    <!-- 查看详情弹窗 -->
    <el-dialog title="学校详情" v-model="detailDialogVisible" width="600px">
      <el-descriptions column="1" border>
        <el-descriptions-item label="学校名称">{{ currentSchool.realName }}</el-descriptions-item>
        <el-descriptions-item label="学校编号">{{ currentSchool.number }}</el-descriptions-item>
        <el-descriptions-item label="学校代码">{{ currentSchool.code }}</el-descriptions-item>
        <el-descriptions-item label="所在地区">
          {{ currentSchool.province }}{{ currentSchool.city }}{{ currentSchool.district }}
        </el-descriptions-item>
        <el-descriptions-item label="详细地址">{{ currentSchool.detailAddress }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentSchool.mobile }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentSchool.status ? 'success' : 'danger'">
            {{ currentSchool.status ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(currentSchool.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="最后登录">{{ formatTime(currentSchool.lastLoginTime) || '从未登录' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑学校弹窗 -->
    <el-dialog title="编辑学校" v-model="editDialogVisible" width="600px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="120px">
        <el-form-item label="学校名称" prop="realName">
          <el-input v-model="editForm.realName" />
        </el-form-item>
        <el-form-item label="学校代码" prop="code">
          <el-input v-model="editForm.code" />
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="editForm.mobile" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="editForm.detailAddress" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch 
            v-model="editForm.status" 
            active-value="true" 
            inactive-value="false"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 审核弹窗（优化版） -->
    <el-dialog title="学校审核" v-model="reviewDialogVisible" width="900px">
      <!-- 审核状态筛选区 -->
      <div class="review-filter-container" style="margin-bottom: 16px;">
        <el-select 
          v-model="reviewStatus" 
          placeholder="选择审核状态" 
          style="width: 220px;"
          :disabled="isReviewLoading"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="未审核" value="0"></el-option>
          <el-option label="已通过" value="1"></el-option>
          <el-option label="未通过" value="2"></el-option>
        </el-select>
        <el-button 
          type="primary" 
          size="small" 
          @click="refreshReviewList"
          :loading="isReviewLoading"
          style="margin-left: 10px;"
        >
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
      </div>

      <!-- 审核表格 -->
      <el-table 
        :data="filteredApprovalSchools" 
        stripe 
        border
        v-loading="isReviewLoading"
        element-loading-text="加载中..."
      >
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="realName" label="学校名称" width="200"></el-table-column>
        <el-table-column prop="number" label="学校编号" width="140"></el-table-column>
        <el-table-column label="地区" width="220">
          <template #default="scope">
            {{ scope.row.province }}{{ scope.row.city }}{{ scope.row.district }}
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="联系电话" width="140"></el-table-column>
        <!-- 审核状态列 -->
        <el-table-column label="审核状态" width="140" align="center">
          <template #default="scope">
            <el-tag 
              :type="getStatusTagType(scope.row.status)"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <template v-if="scope.row.status === 0">
              <div class="review-actions">
                <el-button size="small" type="success" @click="handleApprove(scope.row, 1)">通过</el-button>
                <el-button size="small" type="danger" @click="handleApprove(scope.row, 2)">拒绝</el-button>
              </div>
            </template>
            <template v-else-if="scope.row.status === 1">
              <el-tag type="success">已通过</el-tag>
            </template>
            <template v-else-if="scope.row.status === 2">
              <el-tag type="danger">未通过</el-tag>
            </template>
            <template v-else>
              <el-tag type="info">未知</el-tag>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="reviewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { Search, Check, Refresh,Delete } from '@element-plus/icons-vue';
import { 
  getAllSchoolInformation, 
  updateSchoolStatus,
  updateSchoolInformation,
  getAllSchoolApproval,
  updateSchoolApproval
} from '../../../api/platform-school/platform-school.js';

// 存储选中的学校
const selectedSchools = ref([]);

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedSchools.value = selection;
};

// 批量删除处理
const handleBatchDelete = async () => {
  if (selectedSchools.value.length === 0) {
    ElMessage.warning('请选择需要删除的学校');
    return;
  }

  try {
    // 显示确认弹窗
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedSchools.value.length} 所学校吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'danger'
      }
    );

    // 显示加载状态
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '删除中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 调用批量删除API（假设存在该接口）
    const ids = selectedSchools.value.map(school => school.id);
    await batchDeleteSchools(ids); // 需要在api中引入该方法

    ElMessage.success('批量删除成功');
    // 刷新列表
    fetchSchools();
    // 清空选择
    selectedSchools.value = [];

    // 关闭加载
    loadingInstance.close();
  } catch (error) {
    // 关闭加载
    ElLoading.service().close();
    
    // 取消操作不提示错误
    if (error.toString() !== 'Cancel') {
      ElMessage.error('批量删除失败：' + (error.message || '未知错误'));
      console.error('批量删除错误：', error);
    }
  }
};


// 搜索条件
const searchKeyword = ref('');
const searchStatus = ref('');

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);

// 加载状态
const loading = ref(false);
// 审核列表专用加载状态（解决筛选时的交互问题）
const isReviewLoading = ref(false);

// 学校数据
const schools = ref([]);
const approvalSchools = ref([]); // 原始审核列表

// 弹窗状态
const detailDialogVisible = ref(false);
const editDialogVisible = ref(false);
const reviewDialogVisible = ref(false);

// 当前操作的学校
const currentSchool = ref({});

// 编辑表单数据
const editForm = reactive({
  id: '',
  realName: '',
  code: '',
  mobile: '',
  detailAddress: '',
  status: true
});

// 编辑表单验证规则
const editRules = {
  realName: [
    { required: true, message: '请输入学校名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入学校代码', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  detailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
};

// 编辑表单引用
const editFormRef = ref();

// 审核状态筛选值（优化：确保初始值为字符串类型）
const reviewStatus = ref('0');

// 优化：将状态判断逻辑封装为函数，便于维护
const getStatusText = (status) => {
  const statusMap = {
    0: '未审核',
    1: '已通过',
    2: '未通过'
  };
  return statusMap[status] || '未知';
};

// 优化：状态标签样式函数
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  };
  return typeMap[status] || 'info';
};

// 优化：筛选后的审核列表（增强类型兼容性）
const filteredApprovalSchools = computed(() => {
  // 防御性编程：处理空数据情况
  if (!approvalSchools.value || approvalSchools.value.length === 0) {
    return [];
  }
  
  // 无筛选条件时返回所有数据
  if (!reviewStatus.value) {
    return approvalSchools.value;
  }
  
  // 增强类型转换，确保前后端数据类型一致
  return approvalSchools.value.filter(school => {
    // 同时处理数字和字符串类型的状态值
    return String(school.status) === reviewStatus.value;
  });
});

// 页面加载时获取学校列表
onMounted(() => {
  fetchSchools();
});

// 优化：获取学校列表（增强错误处理）
const fetchSchools = async () => {
  try {
    loading.value = true;
    const data = await getAllSchoolInformation();
    // 验证数据格式
    if (Array.isArray(data)) {
      schools.value = data;
    } else {
      schools.value = [];
      ElMessage.warning('获取的学校列表格式不正确');
    }
  } catch (error) {
    ElMessage.error('获取学校列表失败：' + (error.message || '未知错误'));
    console.error('获取学校列表错误：', error);
  } finally {
    loading.value = false;
  }
};

// 优化：获取审核列表（单独的加载状态，解决筛选交互问题）
const fetchApprovalSchools = async () => {
  try {
    isReviewLoading.value = true;
    const data = await getAllSchoolApproval();
    
    // 验证数据格式并检查是否包含必要字段
    if (Array.isArray(data)) {
      // 检查每个学校是否包含status字段
      const validData = data.map(school => {
        // 确保status存在且为数字
        if (school.status === undefined) {
          console.warn('学校数据缺少status字段：', school);
          return { ...school, status: 0 }; // 默认设为未审核
        }
        // 转换为数字类型
        return { ...school, status: Number(school.status) };
      });
      approvalSchools.value = validData;
    } else {
      approvalSchools.value = [];
      ElMessage.warning('获取的审核列表格式不正确');
    }
  } catch (error) {
    ElMessage.error('获取审核列表失败：' + (error.message || '未知错误'));
    console.error('获取审核列表错误：', error);
  } finally {
    isReviewLoading.value = false;
  }
};

// 刷新审核列表
const refreshReviewList = () => {
  fetchApprovalSchools();
};

// 筛选学校列表
const filteredSchools = computed(() => {
  return schools.value.filter(school => {
    const keywordMatch = !searchKeyword.value || 
      (school.realName && school.realName.includes(searchKeyword.value)) || 
      (school.number && school.number.includes(searchKeyword.value));
    
    let statusMatch = true;
    if (searchStatus.value !== '') {
      statusMatch = String(school.status) === searchStatus.value;
    }
    
    return keywordMatch && statusMatch;
  });
});

// 分页处理
const paginatedSchools = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return filteredSchools.value.slice(startIndex, startIndex + pageSize.value);
});

// 格式化时间显示
const formatTime = (time) => {
  if (!time) return '';
  try {
    return new Date(time).toLocaleString();
  } catch (error) {
    console.error('时间格式化错误：', error);
    return time; // 格式化失败时返回原始值
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 查看学校详情
const handleViewDetail = (school) => {
  if (!school) return;
  currentSchool.value = { ...school };
  detailDialogVisible.value = true;
};

// 编辑学校
const handleEdit = (school) => {
  if (!school) return;
  currentSchool.value = { ...school };
  // 填充编辑表单
  editForm.id = school.id;
  editForm.realName = school.realName || '';
  editForm.code = school.code || '';
  editForm.mobile = school.mobile || '';
  editForm.detailAddress = school.detailAddress || '';
  editForm.status = school.status;
  editDialogVisible.value = true;
};

// 保存编辑
const handleSaveEdit = async () => {
  if (!editFormRef.value) return;
  
  try {
    // 表单验证
    await editFormRef.value.validate();
    const params = {
      realName: editForm.realName,
      code: editForm.code,
      mobile: editForm.mobile,
      detailAddress: editForm.detailAddress,
      status: editForm.status === 'true' || editForm.status === true
    };
    
    // 显示加载动画
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '保存中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // 调用编辑接口
    await updateSchoolInformation(editForm.id, params);
    ElMessage.success('编辑成功');
    editDialogVisible.value = false;
    fetchSchools(); // 重新获取学校列表
    
    // 关闭加载动画
    loadingInstance.close();
  } catch (error) {
    // 关闭加载动画（如果存在）
    ElLoading.service().close();
    
    // 表单验证失败不提示错误
    if (error.name !== 'Error') {
      console.error('表单验证失败:', error);
      return;
    }
    ElMessage.error('编辑失败：' + (error.message || '未知错误'));
    console.error('编辑学校错误：', error);
  }
};

// 更改学校状态
const handleChangeStatus = async (school) => {
  if (!school || !school.id) {
    ElMessage.warning('无效的学校数据');
    return;
  }
  
  const action = school.status ? '禁用' : '启用';
  try {
    // 确认弹窗
    await ElMessageBox.confirm(`确定要${action}「${school.realName || '该学校'}」吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    // 调用状态更新接口
    await updateSchoolStatus(school.id, school.status ? 0 : 1);
    ElMessage.success(`${action}成功`);
    fetchSchools(); // 刷新列表
  } catch (error) {
    // 取消操作不提示错误
    if (error.toString() !== 'Cancel') {
      ElMessage.error(`${action}失败：` + (error.message || '未知错误'));
      console.error(`${action}学校错误：`, error);
    } else {
      ElMessage.info('已取消操作');
    }
  }
};

// 打开审核弹窗
const handleReview = () => {
  fetchApprovalSchools(); // 获取最新审核数据
  reviewDialogVisible.value = true;
};

// 处理审核
const handleApprove = async (school, status) => {
  if (!school || !school.id) {
    ElMessage.warning('无效的学校数据');
    return;
  }
  
  const action = status === 1 ? '通过' : '拒绝';
  try {
    // 确认弹窗
    await ElMessageBox.confirm(`确定要${action}「${school.realName || '该学校'}」的审核吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    // 显示加载动画
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // 调用审核接口
    await updateSchoolApproval(school.id, status);
    ElMessage.success(`审核${action}成功`);
    
    // 刷新列表
    await fetchApprovalSchools();
    fetchSchools();
    
    // 关闭加载动画
    loadingInstance.close();
  } catch (error) {
    // 关闭加载动画
    ElLoading.service().close();
    
    // 取消操作不提示错误
    if (error.toString() !== 'Cancel') {
      ElMessage.error(`审核${action}失败：` + (error.message || '未知错误'));
      console.error(`审核${action}错误：`, error);
    }
  }
};

// 优化：监听审核状态变化，自动更新列表
watch(reviewStatus, (newVal) => {
  // 状态变化时不需要重新请求，仅过滤现有数据
  console.log('审核状态筛选变化为：', newVal);
});
</script>

<style scoped>
/* 全局容器样式 */
.platform-school {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 学校列表卡片样式 */
.school-list-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 卡片标题计数样式 */
.count {
  color: #666;
  font-size: 14px;
  margin-left: 10px;
  font-weight: normal;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 状态徽章样式 */
.status-badge {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}
.status-active {
  background-color: #67c23a;
}
.status-inactive {
  background-color: #f56c6c;
}

/* 文本右对齐 */
.text-right {
  text-align: right;
}

/* 表格操作按钮组样式 */
.table-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 审核弹窗操作按钮组样式 */
.review-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}

/* 审核筛选区样式 */
.review-filter-container {
  display: flex;
  align-items: center;
}

/* 最后登录时间样式 */
.last-login-time {
  color: #909399;
  font-size: 12px;
}
</style>
